﻿using EntityFrameworkCore.Triggered;
using Microsoft.EntityFrameworkCore;
using StockTrading.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static StockTrading.Model.Order;

namespace StockTrading.Triggers
{

    public class MakeTransactions : IBeforeSaveTrigger<Order>
    {
        readonly ApplicationContext _context;
        public MakeTransactions(ApplicationContext context)
        {
            _context = context;
        }
        public Task BeforeSave(ITriggerContext<Order> context, CancellationToken cancellationToken)
        {
            //来得是买单
            if (context.ChangeType == ChangeType.Added && context.Entity.Type == OrderType.Buy)
            {
                //查找用户所拥有的股票
                var userPosition = _context.UserPositions.Where(x => x.UserId == context.Entity.UserId && x.StockId == context.Entity.StockId).FirstOrDefault();
                if (userPosition == null)
                {
                    userPosition = new UserPosition()
                    {
                        StockId = context.Entity.StockId,
                        UserId = context.Entity.UserId,
                        NumFree = 0,
                        NumFreezed = 0,
                    };
                    _context.UserPositions.Add(userPosition);
                    /*                         _context.SaveChanges();*/
                }
                //选出所有价格小于等于新来单价格的卖单，并排序
                var sellOrders = _context.Orders
                .Where(x => x.Type == OrderType.Sell && x.Price <= context.Entity.Price && x.Undealed > 0)
                 .Include(x => x.Stock)
                 .OrderBy(x => x.Price)
                 .ThenBy(x => x.Id)
                 .ToList();

                //开启事务
                /*                    using (var transaction = _context.Database.BeginTransaction())
                                    {*/
                //将用户买单花费转换冻结金额
                var user = _context.Users.Where(x => x.Id == context.Entity.UserId).FirstOrDefault();
                decimal dealCny = context.Entity.Price * context.Entity.Undealed;
                user.CnyFree -= dealCny;
                user.CnyFreezed += dealCny;
                foreach (var sellOrder in sellOrders)
                {
                    //卖单未成交小于当前买单未成交，没买完
                    if (sellOrder.Undealed < context.Entity.Undealed)
                    {
                        //买单未成交减去买单未成交
                        context.Entity.Undealed -= sellOrder.Undealed;
                        //买单成交额加上买单未成交额
                        context.Entity.Dealed += sellOrder.Undealed;
                        //卖单成交额加上卖单全部的未成交额
                        sellOrder.Dealed += sellOrder.Undealed;
                        _context.SaveChanges();
                        //添加到transaction表
                        _context.Transactions.Add(new Transaction()
                        {
                            Buy_OrderId = context.Entity.Id,
                            Sell_OrderId = sellOrder.Id,
                            Dealed = sellOrder.Undealed
                        });
                        //用户冻结金额减少
                        user.CnyFreezed -= sellOrder.Undealed * context.Entity.Price;
                        //用户可用股票数量增加
                        userPosition.NumFree += sellOrder.Undealed;
                        //卖单未成交额清0
                        sellOrder.Undealed = 0;
                        //创建恢复点
                        /*_context.SaveChanges();*/
                    }
                    //买单未成交额小于卖单
                    else
                    {
                        //卖单买完所有未成交
                        sellOrder.Undealed -= context.Entity.Undealed;
                        sellOrder.Dealed += context.Entity.Undealed;
                        //买单完成交易
                        context.Entity.Dealed += context.Entity.Undealed;
                        _context.SaveChanges();
                        //存入transaction表
                        _context.Transactions.Add(new Transaction()
                        {
                            Buy_OrderId = context.Entity.Id,
                            Sell_OrderId = sellOrder.Id,
                            Dealed = context.Entity.Dealed
                        });
                        //冻结金额减少
                        user.CnyFreezed -= context.Entity.Undealed;
                        //用户可用股票数量增加
                        userPosition.NumFree += context.Entity.Undealed;
                        //买单清空
                        context.Entity.Undealed = 0;
                        /*_context.SaveChanges();*/
                        break;
                    }
                }
            }
            //提交事务
            /* transaction.CommitAsync(cancellationToken);
            //触发器完成后会自动挂单
             }*/
            _context.SaveChanges();
            return Task.CompletedTask;
        }

    }
    
}